// pages/task/task.js
const app = getApp();

Page({
  data: {
    eventId: null,
    event: null,
    loading: true,
    refreshing: false,
    activeTab: 0,
    tabs: ['任务信息', '位置信息', '处理记录']
  },

  onLoad(options) {
    console.log('任务页面加载', options);
    if (options.id) {
      this.setData({
        eventId: options.id
      });
      this.loadEventDetail();
    } else {
      app.showError('缺少任务ID');
      wx.navigateBack();
    }
  },

  onShow() {
    console.log('任务页面显示');
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  // 刷新数据
  async refreshData() {
    this.setData({ refreshing: true });
    
    try {
      await this.loadEventDetail();
    } catch (error) {
      console.error('刷新数据失败:', error);
    } finally {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    }
  },

  // 加载任务详情
  async loadEventDetail() {
    if (!this.data.eventId) return;

    this.setData({ loading: true });
    app.showLoading('加载中...');

    try {
      const res = await app.request({
        url: `/api/events/${this.data.eventId}`,
        method: 'GET'
      });

      if (res.data) {
        this.setData({
          event: res.data,
          loading: false
        });
      } else {
        app.showError('任务不存在');
        wx.navigateBack();
      }
    } catch (err) {
      console.error('加载任务详情失败:', err);
      app.showError('加载失败，请重试');
      this.setData({ loading: false });
    } finally {
      app.hideLoading();
    }
  },

  // 切换标签页
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeTab: index
    });
  },

  // 接受任务
  async acceptEvent() {
    const confirmed = await app.showConfirm('确认接受', '确认接受此任务？');
    if (confirmed) {
      await this.updateEventStatus('accept');
    }
  },

  // 开始前往
  async startEnRoute() {
    const confirmed = await app.showConfirm('确认前往', '确认开始前往现场？');
    if (confirmed) {
      await this.updateEventStatus('en-route');
    }
  },

  // 到达现场
  async arriveAtScene() {
    const confirmed = await app.showConfirm('确认到达', '确认已到达现场？');
    if (confirmed) {
      await this.updateEventStatus('arrive');
    }
  },

  // 开始处理
  async startProcessing() {
    const confirmed = await app.showConfirm('确认处理', '确认开始处理任务？');
    if (confirmed) {
      await this.updateEventStatus('start-processing');
    }
  },

  // 完成任务
  async completeTask() {
    const result = await new Promise((resolve) => {
      wx.showModal({
        title: '完成任务',
        content: '请输入完成说明',
        editable: true,
        success: (res) => {
          if (res.confirm) {
            resolve(res.content);
          } else {
            resolve(null);
          }
        }
      });
    });

    if (result !== null) {
      await this.updateEventStatus('complete', result);
    }
  },

  // 更新任务状态
  async updateEventStatus(action, notes = '') {
    if (!this.data.eventId) return;

    app.showLoading('更新中...');

    try {
      let url = '';
      let data = {};

      switch (action) {
        case 'accept':
          url = `/api/events/${this.data.eventId}/accept`;
          break;
        case 'en-route':
          url = `/api/events/${this.data.eventId}/en-route`;
          data = { 
            latitude: app.globalData.currentLocation?.latitude || 0, 
            longitude: app.globalData.currentLocation?.longitude || 0 
          };
          break;
        case 'arrive':
          url = `/api/events/${this.data.eventId}/arrive`;
          data = { 
            latitude: app.globalData.currentLocation?.latitude || 0, 
            longitude: app.globalData.currentLocation?.longitude || 0 
          };
          break;
        case 'start-processing':
          url = `/api/events/${this.data.eventId}/start-processing`;
          break;
        case 'complete':
          url = `/api/events/${this.data.eventId}/complete`;
          data = { completionNotes: notes };
          break;
      }

      const res = await app.request({
        url: url,
        method: 'POST',
        data: data
      });

      if (res.data.success) {
        app.showSuccess('操作成功');
        // 刷新任务详情
        await this.loadEventDetail();
      } else {
        app.showError(res.data.message || '操作失败');
      }
    } catch (err) {
      console.error('更新任务状态失败:', err);
      app.showError('操作失败，请重试');
    } finally {
      app.hideLoading();
    }
  },

  // 查看地图
  viewMap() {
    const { event } = this.data;
    if (event && event.latitude && event.longitude) {
      wx.openLocation({
        latitude: event.latitude,
        longitude: event.longitude,
        name: event.title || '任务地点',
        address: event.address || '任务地址'
      });
    } else {
      app.showError('暂无位置信息');
    }
  },

  // 拨打电话
  makeCall() {
    const { event } = this.data;
    if (event && event.contactPhone) {
      wx.makePhoneCall({
        phoneNumber: event.contactPhone
      });
    } else {
      app.showError('暂无联系电话');
    }
  },

  // 复制信息
  copyInfo(e) {
    const text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: () => {
        app.showSuccess('已复制到剪贴板');
      }
    });
  },

  // 返回主页
  goHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  }
}); 